'''
<template>
  <div class="translate-container">
    <!-- 左侧输入面板 -->
    <div class="pane input-pane">
      <div class="language-selectors">
        <el-select v-model="sourceLang" size="small" class="lang-select">
          <el-option
            v-for="item in sourceLanguages"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <el-button
          :icon="Switch"
          circle
          @click="swapLanguages"
          size="small"
          class="swap-btn"
        ></el-button>
        <el-select v-model="targetLang" size="small" class="lang-select">
          <el-option
            v-for="item in targetLanguages"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </div>
      <el-input
        ref="inputRef"
        v-model="inputText"
        type="textarea"
        :autosize="{ minRows: 5 }"
        placeholder="请输入要翻译的文本"
        class="input-textarea"
        resize="none"
        :maxlength="4000"
        show-word-limit
      ></el-input>
      <div class="input-actions">
        <el-button
          type="primary"
          @click="handleTranslate"
          class="translate-btn"
          :disabled="!inputText.trim()"
        >
          翻译
        </el-button>
      </div>
    </div>

    <!-- 右侧结果面板 -->
    <div class="pane result-pane">
      <div class="result-content" v-loading="loading">
        <div v-if="translationError" class="error-message">
          <el-alert
            :title="`翻译出错 (${translationError.code})`"
            type="error"
            :description="translationError.message"
            show-icon
            :closable="false"
          ></el-alert>
        </div>
        <div v-else>
          {{ resultText }}
        </div>
      </div>
      <div class="result-actions">
        <template v-if="targetLang === 'en'">
          <!-- 小驼峰 -->
          <el-button circle @click="toSmallCamel" :disabled="!resultText">
            小
          </el-button>
          <!-- 大驼峰 -->
          <el-button circle @click="toBigCamel" :disabled="!resultText">
            大
          </el-button>
          <!-- 原始 -->
          <el-button circle @click="toOriginal" :disabled="!resultText">
            源
          </el-button>
        </template>
        <!-- 复制按钮 -->
        <el-button
          :icon="DocumentCopy"
          circle
          @click="copyResult"
          :disabled="!resultText"
        ></el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from "vue";
import { ElMessage } from "element-plus";
import { DocumentCopy, Switch } from "@element-plus/icons-vue";
import { invoke } from "@tauri-apps/api/core";
import { getCurrentWindow } from "@tauri-apps/api/window";

// 翻译缓存 (内存)
const translationCache = new Map<string, string>();

// 输入和输出文本
const inputText = ref("");
const resultText = ref("");
let currentResultTextCache = ""; // 当前结果文本缓存
const inputRef = ref<any>(null);

// 加载和错误状态
const loading = ref(false);
const translationError = ref<{ code: string; message: string } | null>(null);

// 语言选项
const sourceLang = ref("auto");
const targetLang = ref("en");

const sourceLanguages = ref([
  { value: "auto", label: "自动检测" },
  { value: "zh", label: "中文" },
  { value: "en", label: "英语" },
  { value: "ja", label: "日语" },
  { value: "ko", label: "韩语" },
]);

const targetLanguages = ref([
  { value: "zh", label: "中文" },
  { value: "en", label: "英语" },
  { value: "ja", label: "日语" },
  { value: "ko", label: "韩语" },
]);

/**
 * @description 交换源语言和目标语言
 */
const swapLanguages = () => {
  if (sourceLang.value === "auto") return;
  const temp = sourceLang.value;
  sourceLang.value = targetLang.value;
  targetLang.value = temp;
};

/**
 * @description 调用Tauri后端执行翻译，包含缓存和重试逻辑
 */
const handleTranslate = async () => {
  const textToTranslate = inputText.value.trim();
  if (!textToTranslate) return;

  // 1. 检查缓存
  const cacheKey = `${textToTranslate}|${sourceLang.value}|${targetLang.value}`;
  if (translationCache.has(cacheKey)) {
    currentResultTextCache = translationCache.get(cacheKey)!;
    resultText.value = currentResultTextCache;
    translationError.value = null;
    return;
  }

  loading.value = true;
  resultText.value = "";
  currentResultTextCache = "";
  translationError.value = null;

  try {
    const response: any = await invoke("translate", {
      text: textToTranslate,
      sourceLang: sourceLang.value === "auto" ? "" : sourceLang.value,
      targetLang: targetLang.value,
    });

    if (response.response_metadata && response.response_metadata.error) {
      // 请求失败
      const apiError = response.response_metadata.error;
      translationError.value = {
        code: apiError.code,
        message: apiError.message,
      };
    } else if (response.TranslationList && response.TranslationList.length) {
      // 请求成功
      const translation = response.TranslationList[0].Translation;
      currentResultTextCache = translation;
      resultText.value = translation;
      translationCache.set(cacheKey, translation); // Store in cache
    } else {
      // 请求失败
      throw new Error("API未返回有效的翻译结果或响应格式不正确。");
    }
  } catch (err: any) {
    // 请求失败
    translationError.value = {
      code: "InvokeError",
      message:
        err.message || (typeof err === "string" ? err : JSON.stringify(err)),
    };
  } finally {
    loading.value = false;
  }
};

/**
 * @description 复制翻译结果到剪贴板
 */
const copyResult = () => {
  if (!resultText.value) return;
  navigator.clipboard
    .writeText(resultText.value)
    .then(() => {
      ElMessage.success("已复制到剪贴板");
    })
    .catch((err) => {
      console.error("复制失败:", err);
      ElMessage.error("复制失败，请稍后重试");
    });
};

// 处理键盘事件
const handleKeyDown = async (event: KeyboardEvent) => {
  if (event.key === "Escape" || event.key === "Esc") {
    try {
      await invoke("close_current_window");
    } catch (e) {
      console.error("关闭窗口失败:", e);
    }
  }
};

/**
 * @description 将翻译结果转换为小驼峰
 */
const toSmallCamel = () => {
  if (!currentResultTextCache) return;
  const words = currentResultTextCache.trim().split(/\s+/);
  resultText.value = words
    .map((word: string, index: number) => {
      if (index === 0) {
        return word.charAt(0).toLowerCase() + word.slice(1).toLowerCase();
      }
      return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
    })
    .join("");
};

/**
 * @description 将翻译结果转换为大驼峰
 */
const toBigCamel = () => {
  if (!currentResultTextCache) return;
  const words = currentResultTextCache.trim().split(/\s+/);
  resultText.value = words
    .map((word: string, index: number) => {
      if (index === 0) {
        return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
      }
      return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
    })
    .join("");
};

/**
 * @description 将翻译结果转换为原始文本
 */
const toOriginal = () => {
  if (!currentResultTextCache) return;
  resultText.value = currentResultTextCache;
};

// 窗口失焦监听解除函数
let unlistenBlur: (() => void) | null = null;

// 处理窗口失焦事件
const handleWindowBlur = async () => {
  try {
    // 获取翻译配置
    const config = await invoke<any>("get_app_config");
    const translateConfig = config?.translate;

    // 如果开启了自动关闭，则关闭窗口
    if (translateConfig?.auto_close === true) {
      await invoke("close_current_window");
    }
  } catch (error) {
    console.error("处理窗口失焦失败:", error);
  }
};

onMounted(async () => {
  window.addEventListener("keydown", handleKeyDown);

  // 监听窗口失焦事件
  const currentWindow = getCurrentWindow();
  currentWindow
    .onFocusChanged(({ payload: focused }) => {
      if (!focused) {
        // 窗口失去焦点
        handleWindowBlur();
      }
    })
    .then((unlisten) => {
      unlistenBlur = unlisten;
    })
    .catch((error) => {
      console.error("❌ 监听窗口失焦事件失败:", error);
    });

  // 等待 DOM 渲染完成后聚焦输入框
  await nextTick();
  if (inputRef.value) {
    // Element Plus 的 textarea 组件，需要通过 textarea 属性访问原生 textarea 元素
    const textarea =
      inputRef.value.textarea || inputRef.value.$el?.querySelector("textarea");
    if (textarea) {
      textarea.focus();
    } else {
      // 备用方案：直接调用组件的 focus 方法
      inputRef.value.focus?.();
    }
  }
});

onUnmounted(() => {
  window.removeEventListener("keydown", handleKeyDown);

  // 解除窗口失焦监听
  if (unlistenBlur) {
    unlistenBlur();
  }
});
</script>

<style scoped>
.translate-container {
  display: flex;
  gap: 20px;
  padding: 20px;
  height: 100vh;
  box-sizing: border-box;
}

.pane {
  flex: 1;
  display: flex;
  flex-direction: column;
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  overflow: hidden;
  background-color: #fff;
}

.input-pane {
  gap: 10px;
}

.language-selectors {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 12px;
  background-color: #f7f8fa;
  border-bottom: 1px solid #dcdfe6;
}

.lang-select {
  width: 120px;
}

.swap-btn {
  margin: 0 10px;
}

.input-textarea {
  flex: 1;
}

.input-actions {
  padding: 8px 12px;
  text-align: right;
  border-top: 1px solid #dcdfe6;
}

.translate-btn {
  width: 100px;
}

.result-pane {
  justify-content: space-between;
}

.result-content {
  flex: 1;
  padding: 12px;
  font-size: 16px;
  line-height: 1.6;
  color: #303133;
  overflow-y: auto;
}

.error-message {
  padding: 20px;
}

.result-actions {
  padding: 8px 12px;
  text-align: right;
  border-top: 1px solid #dcdfe6;
  background-color: #f7f8fa;
}

/* 响应式布局：屏幕宽度小于640px时，垂直排列 */
@media (max-width: 640px) {
  .translate-container {
    flex-direction: column;
    height: auto;
  }
}

/* 深度选择器，用于修改Element Plus组件内部样式 */
:deep(.el-textarea__inner) {
  border: none !important;
  box-shadow: none !important;
  height: 100%;
  padding: 12px;
  font-size: 16px;
}

:deep(.el-select .el-input__inner) {
  border-radius: 15px;
}
</style>
'''
